#include "thread.h"

#ifdef USE_PTHREAD
#include <pthread.h>

namespace org {
namespace antban {
namespace thread {

Thread::Thread() {
	m_pThreadInfo = new char[sizeof(pthread_t)];
	m_Running = false;
}

Thread::~Thread() {
	delete [] (char*)m_pThreadInfo;
}

bool Thread::isRunning() {
	return m_Running;
}

void Thread::run() {
	m_Command->run();
}

ptr::Ptr<Thread> Thread::start(
	Runnable* pCommand) {

	ptr::Ptr<Thread> thread;
	if (0 == pCommand) {
		return thread;
	}

	thread = new Thread();

	bool success = 0 == ::pthread_create((pthread_t*)thread->m_pThreadInfo, 0, Thread::threadFunc, (Thread*)thread);
	if (!success) {
		thread = (Thread*)0;
	}

	return thread;
}

void* Thread::threadFunc(void* pArg) {
	// This variable locks thread deletion until thread finish.
	ptr::Ptr<Thread> threadHolder = (Thread*) pArg;
	threadHolder->m_Running = true;
	threadHolder->run();
	threadHolder->m_Running = false;
	pthread_exit(0);
}

} // namespace thread
} // namespace antban
} // namespace org
#endif USE_PTHREAD
